<title>服务接口管理</title>
<div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
        <a><cite>接口管理</cite></a>
        <a><cite>服务接口管理</cite></a>
    </div>
</div>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-form layui-card-header layuiadmin-card-header-auto" lay-filter="content-pdr-api">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select name="pdrProjectId" id="pdrProjectIdList">
                            <option value="">请选择所属服务项目</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <input type="text" name="name" placeholder="接口名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <input type="text" name="code" placeholder="接口编码" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <input type="text" name="path" placeholder="接口路径" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select name="queryType" id="queryType">
                            <option value="">请选择请求类型</option>
                            <option value="GET">GET</option>
                            <option value="PUT">PUT</option>
                            <option value="POST">POST</option>
                            <option value="DELETE">DELETE</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <div class="layui-input-inline">
                        <select name="publishStatus">
                            <option value="">请选择发布状态</option>
                            <option value="0">待发布</option>
                            <option value="1">已发布</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn layuiadmin-btn-pdr-api" lay-submit lay-filter="LAY-pdr-api-search">
                        搜索
                    </button>
                    <button class="layui-btn pdr-api-btn-common" data-type="add">
                        添加
                    </button>
                </div>
            </div>
        </div>
        <div class="layui-card-body">
            <div class="lay-batch-publish" style="margin-bottom: 5px;">
                <button class="layui-btn layui-btn-warm layui-btn-sm" data-events="batchPublish">
                    <i class="layui-icon layui-icon-release"></i>批量发布
                </button>
            </div>
            <table id="LAY-pdr-api" lay-filter="LAY-pdr-api"></table>
            <script type="text/html" id="publishStatusTpl">
                {{#  if(d.publishTime == 0){ }}
                <span style="color: #DD691D;">未发布</span>
                {{#  } else if(d.publishTime > d.keyUpdateTime){ }}
                <span style="color: #1E9FFF;">已发布</span>
                {{#  } else{ }}
                <span style="color: #CF1900;">待发布</span>
                {{#  } }}
            </script>
            <script type="text/html" id="table-system-pdr-api">
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i
                        class="layui-icon layui-icon-edit"></i>编辑</a>
                <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="publish"><i
                        class="layui-icon layui-icon-release"></i>发布</a>
                <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">
                    <i class="layui-icon layui-icon-about"></i>详情
                </a>
            </script>
        </div>
    </div>
</div>

<script>
    layui.use(['admin', 'table', 'form', 'setter', 'element'], function () {
        var $ = layui.$
            , admin = layui.admin
            , view = layui.view
            , table = layui.table
            , form = layui.form
            , element = layui.element
            , setter = layui.setter;

        var apiUrl = setter.apiUrl;

        admin.req({
            url: apiUrl + '/mapi/producer/drop/list'
            , method: 'post'
            , data: {}
            , done: function (response) {
                if (response.code === 0) {
                    let dropList = response.data;
                    for (let i = 0; i < dropList.length; i++) {
                        let item = dropList[i];
                        let html = "<option value='" + item.id + "'>" + item.name + "</option>";
                        $('#pdrProjectIdList').append(html);
                        console.log(html);
                    }
                    form.render('select');
                } else {
                    layer.msg(response.msg, {
                        offset: '15px', icon: 2
                    });
                }
            }
        });

        table.render({
            elem: '#LAY-pdr-api'
            , url: apiUrl + '/mapi/interface/list'
            , method: 'post'
            , page: true
            , contentType: 'application/json'
            , headers: {'token': layui.data(setter.tableName).token}
            , request: {
                pageName: 'pageNo'
                , limitName: 'pageSize'
            }
            , response: {
                statusCode: 0, //规定数据状态的字段名称，默认：code
            }
            , parseData: function (res) {
                if (res.code === 0) {
                    //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                } else {
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.msg, //解析提示文本
                    };
                }
            }
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'name', width: 120, title: '名称'}
                , {field: 'code', width: 280, title: '编码'}
                , {field: 'queryType', width: 70, title: '类型'}
                , {field: 'path', width: 150, title: '路径'}
                , {field: 'enable', width: 60, title: '可达', templet: '<div>{{d.enable==0?"禁用":"正常"}}</div>'}
                , {
                    field: 'publishStatus',
                    title: '状态',
                    width: 90,
                    templet: '#publishStatusTpl'
                }
                , {title: '操作', minWidth: 220, fixed: 'right', toolbar: '#table-system-pdr-api'}
            ]]
            , text: {
                none: '未检索到数据'
            }
            , done: function () {
            }
        });

        //监听工具条
        table.on('tool(LAY-pdr-api)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                admin.popup({
                    title: '编辑服务接口'
                    , area: ['70%', '100%']
                    , id: 'LAY-popup-pdr-api-edit'
                    , success: function (layero, index) {
                        view(this.id).render('interface/api/edit', data).done(function () {
                            var pid = data.id;
                            form.render(null, 'form-pdr-api');
                            //监听提交
                            form.on('submit(LAY-pdr-api-edit-submit)', function (data) {
                                var formData = data.field;
                                console.log(data.field);

                                formData['hystrixParam'] = {
                                    "commandKey": formData['commandKey'],
                                    "errorThresholdPercentage": formData['errorThresholdPercentage'],
                                    "groupKey": formData['groupKey'],
                                    "requestVolumeThreshold": formData['requestVolumeThreshold'],
                                    "sleepWindowInMilliseconds": formData['sleepWindowInMilliseconds'],
                                    "timeoutInMilliseconds": formData['timeoutInMilliseconds']
                                };

                                console.log(formData);
                                delete formData['groupKey'];
                                delete formData['commandKey'];
                                delete formData['timeoutInMilliseconds'];
                                delete formData['requestVolumeThreshold'];
                                delete formData['sleepWindowInMilliseconds'];
                                delete formData['errorThresholdPercentage'];

                                console.log(formData);
                                admin.req({
                                    url: apiUrl + '/mapi/interface/update/' + pid
                                    , method: 'put'
                                    , data: JSON.stringify(data.field)
                                    , done: function (response) {
                                        if (response.code === 0) {
                                            layer.msg('修改成功', {
                                                offset: '15px', icon: 1, time: 1000
                                            }, function () {
                                                layui.table.reload('LAY-pdr-api');
                                                layer.close(index);
                                            });
                                        } else {
                                            layer.msg(response.msg, {
                                                offset: '15px', icon: 2
                                            });
                                        }
                                    }
                                });
                            });
                        });
                    }
                });
            } else if (obj.event === 'detail') {
                admin.popup({
                    title: '服务接口详情'
                    , area: ['70%', '100%']
                    , id: 'LAY-popup-pdr-api-detail'
                    , success: function (layero, index) {
                        view(this.id).render('interface/api/detail', data).done(function () {
                            form.render(null, 'form-pdr-api');
                        });
                    }
                });
            } else if (obj.event === 'publish') {
                top.layer.confirm('确定要发布【' + data.name + '】接口吗？', {
                        skin: 'layui-layer-admin'
                    }, function (index) {
                        top.layer.close(index);
                        admin.req({
                            url: apiUrl + '/mapi/interface/publish/' + data.id
                            , method: 'get'
                            , done: function (response) {
                                if (response.code === 0) {
                                    layer.msg('发布成功', {
                                        offset: '15px', icon: 1, time: 1000
                                    }, function () {
                                        layui.table.reload('LAY-pdr-api'); //重载表格
                                    });
                                } else {
                                    layer.msg(response.msg, {
                                        offset: '15px', icon: 2
                                    });
                                }
                            }
                        });
                    }
                );
            }
        });

        //事件
        var active = {
            add: function () {
                admin.popup({
                    title: '添加服务接口'
                    , area: ['70%', '100%']
                    , id: 'LAY-popup-pdr-api-add'
                    , success: function (layero, index) {
                        view(this.id).render('interface/api/add').done(function () {
                            //监听提交
                            form.on('submit(LAY-pdr-api-add-submit)', function (data) {
                                var formData = data.field;
                                console.log(data.field);

                                formData['hystrixParam'] = {
                                    "commandKey": formData['commandKey'],
                                    "errorThresholdPercentage": formData['errorThresholdPercentage'],
                                    "groupKey": formData['groupKey'],
                                    "requestVolumeThreshold": formData['requestVolumeThreshold'],
                                    "sleepWindowInMilliseconds": formData['sleepWindowInMilliseconds'],
                                    "timeoutInMilliseconds": formData['timeoutInMilliseconds']
                                };

                                console.log(formData);
                                delete formData['groupKey'];
                                delete formData['commandKey'];
                                delete formData['timeoutInMilliseconds'];
                                delete formData['requestVolumeThreshold'];
                                delete formData['sleepWindowInMilliseconds'];
                                delete formData['errorThresholdPercentage'];

                                console.log(formData);

                                admin.req({
                                    url: apiUrl + '/mapi/interface/add'
                                    , method: 'post'
                                    , data: JSON.stringify(formData)
                                    , done: function (response) {
                                        if (response.code === 0) {
                                            layer.msg('添加成功', {
                                                offset: '15px', icon: 1, time: 1000
                                            }, function () {
                                                layui.table.reload('LAY-pdr-api');
                                                layer.close(index);
                                            });
                                        } else {
                                            layer.msg(response.msg, {
                                                offset: '15px', icon: 2
                                            });
                                        }
                                    }
                                });
                            });
                        });
                    }
                });
            }
        };


        form.render(null, 'content-pdr-api');

        //监听搜索
        form.on('submit(LAY-pdr-api-search)', function (data) {
            var field = data.field;
            //执行重载
            table.reload('LAY-pdr-api', {
                where: field
            });
        });

        $('.layui-btn.pdr-api-btn-common').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });


        var events = {
            batchPublish: function () {
                var checkStatus = table.checkStatus('LAY-pdr-api')
                    , data = checkStatus.data;
                if (data.length === 0) return layer.msg('请先选择需要发布的接口');
                var ids = [];
                for (var i = 0; i < data.length; i++) {
                    ids.push(data[i].id);
                }
                top.layer.confirm('确定要批量发布接口吗？', {
                    skin: 'layui-layer-admin'
                }, function (index) {
                    top.layer.close(index);
                    admin.req({
                        url: apiUrl + '/mapi/interface/publish/batch'
                        , method: 'post'
                        , data: JSON.stringify(ids)
                        , done: function (response) {
                            if (response.code === 0) {
                                layer.msg('批量发布成功', {
                                    offset: '15px', icon: 1, time: 1000
                                }, function () {
                                    layui.table.reload('LAY-pdr-api');
                                });
                            } else {
                                layer.msg(response.msg, {
                                    offset: '15px', icon: 2
                                });
                            }
                        }
                    });
                });
            }
        };

        $('.lay-batch-publish .layui-btn').on('click', function () {
            var thisEvent = $(this).data('events');
            events[thisEvent] && events[thisEvent].call(this);
        });

        function isEmpty(str) {
            if (typeof str == null || str == "" || str == "undefined") {
                return true;
            } else {
                return false;
            }
        }
    });
</script>